#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <functional>
#include <fstream>
#include <set>
#include <stdio.h>
#include <cstring>
#include <cstdio>
#include "Log.hpp"
#include "InetAddr.hpp"
using namespace log_ns;
class Command
{
public:
    Command() // 白名单
    {
        _safe_command.insert("ls");
        _safe_command.insert("touch"); 
        _safe_command.insert("pwd");
        _safe_command.insert("whoami");
        _safe_command.insert("which");
    }
    bool SafeCheck(const std::string &cmdstr)
    {
        for (auto &cmd : _safe_command)
        {
            if (strncmp(cmd.c_str(), cmdstr.c_str(), cmdstr.size()) == 0)
            {
                return true;
            }
        }
        return false;
    }
    std::string Execute(const std::string &cmdstr)
    {
        if (SafeCheck(cmdstr))
            ;
        {
            return "unsafe";
        }
        std::string result;
        FILE *fp = popen(cmdstr.c_str(), "r");
        if (fp)
        {
            char line[1024];
            while (fgets(line, sizeof(line), fp))
            {
                result += line;
            }
            return result.empty() ? "success" : result;
        }
        return "Execute error";
    }
    void HanderCommand(int sockfd, InetAddr addr)
    {
        while (true)
        {
            char commbuff[1024];
            // 1.接收消息
            ssize_t n = ::recv(sockfd, commbuff, sizeof(commbuff) - 1, 0);
            if (n > 0)
            {
                commbuff[n] = 0;
                LOG(INFO, "get command from client[%s],command:%s\n", addr.AddrStr().c_str(), commbuff);
                std::string result = Execute(commbuff);
                // 2.发送消息
                ::send(sockfd, result.c_str(), result.size(), 0);
            }
            else if (n == 0)
            {
                LOG(INFO, "client %s quit\n", addr.AddrStr().c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error\n", addr.AddrStr().c_str());
                break;
            }
        }
    }
    ~Command();

private:
    std::set<std::string> _safe_command;
};